package com.qsl.ssyx.search.receiver;

import com.qsl.ssyx.constant.MqConst;
import com.qsl.ssyx.search.service.SkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * mq消费者
 */
@Component
public class SkuReceiver {

    @Autowired
    private SkuService skuService;


    // 商品上架   -RabbitMQ监听器，绑定监听 ==> 队列，交换机，路由key
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, declare = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void upperSku(Long skuId, Message message, Channel channel) throws IOException {
        System.out.println("=====调用商品上架方法======> "+skuId);
        if (skuId != null) {
            // 调用商品上架方法
            skuService.upperSku(skuId);
        }
        /** 手动应答
         * 1.消息的标记  tag(ID）
         * 2.是否批量应答
         false:只应答接收到的消息:
         true：应答所有消息包括传递过来的消息:*/
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    // 商品下架   -RabbitMQ监听器，绑定监听 ==> 队列，交换机，路由key
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, declare = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
            key = {MqConst.ROUTING_GOODS_LOWER}))
    public void lower(Long skuId, Message message, Channel channel) throws IOException {
        if (skuId != null) {
            // 调用商品下架方法
            skuService.lowerSku(skuId);
        }
        /** 手动应答
         * 1.消息的标记  tag(ID）
         * 2.是否批量应答
         false:只应答接收到的消息:
         true：应答所有消息包括传递过来的消息:*/
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
